/**
 * 清除会话
 * @param
 */
function clearSession() {
  const keys = document.cookie.match(/[^ =;]+(?=\=)/g)
  if (keys) {
    for (let i = keys.length; i--; )
      document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
  }
  sessionStorage.clear()
  localStorage.clear()
}

/**
 * SSO登入登出
 * @param SSOtype
 * login登入
 * logout登出
 */
export function handleSSO(SSOtype: string): string {
  const hostStr = window.location.host.includes('58v5.cn')
    ? 'passport-cloud.58v5.cn'
    : 'passport.58corp.com'
  clearSession()
  return `https://${hostStr}/${SSOtype}?service=` + encodeURIComponent(window.location.origin)
}

/**
 * 转换时间 MM-DD
 * @param dateTime 时间戳
 * @param type 时间格式
 */
export function timetrans(dateTime: any, type: string) {
  const date = new Date(dateTime)
  var Y = date.getFullYear() + '-'
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ''
  var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
  var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
  var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  if (type == 'yyyy-MM-DD') {
    return Y + M + D
  } else {
    return M + D
  }
}

/**
 * 唯一Id
 * @param length 长度
 */
export function uuid(length = 8) {
  const s: any[] = []
  const hexDigits = '0123456789abcdef'
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = ''

  const uuid = s.join('')
  return uuid.slice(0, length)
}
